package com.tn.controller.producer;

import com.tn.socket.ChatClient;
import com.tn.socket.SocketProperties;
import com.tn.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @ClassName TestCntroller
 * @Description TODO
 * @Author Yezhongzhu
 * @Date 2021/12/30 10:54
 * @Version v1.0
 **/
@RestController
@RequestMapping("/")
@Slf4j
public class SocketTestRestful{
    @Resource
    private SocketProperties properties;

    @Resource
    private ThreadPoolExecutor pool;

    private  Socket socket=null;

    private Socket initSocket() throws Exception{
        if(null==socket){
            socket=new Socket("localhost",properties.getPort());
        }
        return socket;
    }

    @RequestMapping("test")
    public String test(String str) {
        String result = "";
        ChatClient chatClient = new ChatClient();
        chatClient.launchFrame("127.0.0.1",2323);
        return result;
    }

    private String sendMesg(String str) {
        String result = "";
        DataOutputStream out=null;
        boolean connFlag = true;
        try {
            Socket sockets=new Socket("localhost",properties.getPort());
            //socket.bind(so);
            //开始连接这个嵌套字
            //socket.connect(so);
            //发送消息
            while (connFlag){
                log.info("============");
                out= new DataOutputStream(sockets.getOutputStream());
                //输入文字
                out.writeBytes(str);
                out.flush();
                //接收信息
                DataInputStream in= new DataInputStream(initSocket().getInputStream());
                result=in.readLine();
                int i = result.lastIndexOf("\r\n");
                result.lastIndexOf("s");
                if(0<=i){
                    log.info("=======消息传送结束=====：{}", result + DateUtil.dateToString(new Date()));
                    connFlag = false;
                }
            }
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
        }
        return result;
    }
}
